/*
 * Copyright 2008 - 2009 Lars Heuer (heuer[at]semagia.com). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.semagia.atomico.server.impl.restlet.resources;

import java.util.List;

import org.restlet.data.Form;
import org.restlet.util.Series;

import com.semagia.atomico.MediaType;
import com.semagia.atomico.MediaType.Parameter;

/**
 * Provides utility functions to convert a {@link MediaType} into a 
 * {@link org.restlet.data.MediaType} and vice versa.
 * 
 * @author Lars Heuer (heuer[at]semagia.com) <a href="http://www.semagia.com/">Semagia</a>
 * @version $Rev: 66 $ - $Date: 2010-09-06 15:29:07 +0000 (Mon, 06 Sep 2010) $
 */
public final class MediaTypeUtils {

    private MediaTypeUtils() {
        // noop.
    }

    /**
     * Converts an Atomico MediaType into a Restlet MediaType.
     *
     * @param mediaType The Atomico media type.
     * @return The equivalent media type instance for Restlet.
     */
    public static org.restlet.data.MediaType toRestletMediaType(MediaType mediaType) {
        return new org.restlet.data.MediaType(mediaType.getType() + "/" + mediaType.getSubtype(), 
                toSeries(mediaType.getParameters()));
    }

    /**
     * Converts a Restlet MediaType into an Atomico MediaType.
     *
     * @param mediaType The media type to convert.
     * @return The converted media type.
     */
    public static MediaType toAtomicoMediaType(org.restlet.data.MediaType mediaType) {
        return MediaType.valueOf(mediaType.toString());
    }

    /**
     * Converts the parameters into a Restlet Series.
     *
     * @param parameters The parameters to convert.
     * @return A Series representing the provided media types.
     */
    private static Series<org.restlet.data.Parameter> toSeries(List<Parameter> parameters) {
        Form form = new Form(parameters.size());
        for (Parameter param: parameters) {
            form.add(param.getKey(), param.getValue());
        }
        return form;
    }

}
